<?php

namespace app\erp\controller;

use JdMediaSdk\JdFatory;
use QL\QueryList;
use app\erp\model\Jddb;
use app\erp\model\Uploaddb;
use app\erp\model\Branddb;
use app\erp\model\CategoryBranddb;
use app\erp\model\Goodsdb;
use app\erp\model\Attrdb;
use app\erp\model\AttrValuedb;
use app\erp\model\SalePricedb;
use think\Cache;
use app\erp\model\Jdpricedb;
use UnionOpenGoodsLinkQuery\GoodsReq;

class Jdgoods extends Base
{
    protected $db;
    protected $cols = array(
        array(
            'field' => 'jd_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'jd_id',
            'width' => 100,
            'title' => 'ID',
            'hide' => 'true'
        ),
        array(
            'field' => 'spu',
            'width' => 160,
            'title' => '采集编号'
        ),
        array(
            'field' => 'goods_name',
            'width' => 300,
            'title' => '商品名称'
        ),
        array(
            'field' => 'goods_model',
            'width' => 160,
            'title' => '商品型号'
        ),
        array(
            'field' => 'brand_name',
            'width' => 120,
            'title' => '品牌'
        ),
        array(
            'field' => 'goods_unit',
            'width' => 120,
            'title' => '单位'
        ),
        array(
            'field' => 'product_area',
            'width' => 160,
            'title' => '产地'
        ),
        array(
            'field' => 'price',
            'width' => 120,
            'title' => '采集价格'
        ),
        array(
            'field' => 'goods_sku',
            'width' => 160,
            'title' => '入库编号'
        ),
        array(
            'fixed' => 'right',
            'width' => 80,
            'toolbar' => '#jdgoods_tool',
            'title' => '操作'
        )
    );
    public $post = array();
    protected $config = [
        'appkey' => '8a13ee6e602e39355ca3ac4ee05e24ac', // AppId （京东联盟的appkey）
        'appSecret' => 'ee3b7e41ac494be4b1aaf74b26a5fe2e', // 密钥 （京东联盟的appSecret）
        'unionId' => '', // 联盟ID （如果使用京东联盟的，填京东联盟的，使用京佣的填京佣的）
        'positionId' => '', // 推广位ID （如果使用京东联盟的，填京东联盟的，使用京佣的填京佣的）
        'siteId' => '', // 网站ID, （如果使用京东联盟的，填京东联盟的，使用京佣的填京佣的）
        'apithId' => '',  // 第三方网站Apith的appid （可选，不使用apith的，可以不用填写）
        'apithKey' => '', // 第三方网站Apith的appSecret (可选，不使用apith的，可以不用填写)
        'jyCode' => '', // 京东京佣的API授权调用code (可选，不使用京佣的，可以不用填写)
        'isCurl' => true // 设置为true的话，强制使用php的curl，为false的话，在swoole cli环境下自动启用 http协程客户端
    ];

    public function _initialize()
    {
        parent::_initialize();
        Vendor('jdsdk.jd.JdClient');
        Vendor('jdsdk.jd.request.UnionOpenGoodsPromotiongoodsinfoQueryRequest');
        Vendor('jdsdk.jd.request.UnionOpenGoodsBigfieldQueryRequest');
        Vendor('jdsdk.jd.request.domain.UnionOpenGoodsBigfieldQuery.GoodsReq');
        Vendor('jdsdk.jd.request.domain.UnionOpenGoodsSeckillQuery.GoodsReq');
        Vendor('jdsdk.jd.request.domain.UnionOpenGoodsLinkQuery.GoodsReq');
        $request = request();
        $param = $request->param();
        $this->post = $param;
        $this->db = new Jddb ();
        $this->db->param = $this->post;
    }

    public function index()
    {
        $this->assign('cols', json_encode($this->cols));
        return $this->fetch();
    }

    public function ajaxList()
    {
        $return = $this->db->ajaxSelect();
        $this->layuiReturn($return ['data'], $return ['count']);
    }

    public function collect()
    {
        return $this->fetch();
    }

    public function price($page = 1, $limit = 100)
    {
        set_time_limit(0);
        $jddb = new Jddb ();
        $jddb->param ['page'] = $page;
        $jddb->param ['limit'] = $limit;
        $get_jd = $jddb->ajaxList();
        $ql = new QueryList ();
        $jdpricedb = new Jdpricedb ();
        $jdpricedb->ajaxDelete();
        foreach ($get_jd as $key => $val) {
            // 价格
            $price_url = 'https://pe.3.cn/prices/mgets?skuids=' . $val ['spu'];
            $goods_price = $ql->get($price_url)->getHtml();
            $price = json_decode($goods_price, true);
            $price = $price [0] ['p'];
            if ($val ['new_price'] != $price) {
                $temp ['goods_sku'] = $val ['goods_sku'];
                $temp ['goods_name'] = $val ['goods_name'];
                $temp ['old_price'] = $val ['new_price'];
                $temp ['new_price'] = $price;
                $jdpricedb->ajaxSave();
                $jddb->where('jd_id', $val ['jd_id'])->update(array(
                    'new_price' => $price
                ));
            }
        }
        $this->layuiReturn('success');
    }

    public function baseCollectx($spu)
    {
        $jdc = new \JdClient();
        $jdc->appKey = '8a13ee6e602e39355ca3ac4ee05e24ac';
        $jdc->appSecret = 'ee3b7e41ac494be4b1aaf74b26a5fe2e';
        $jdc->accessToken = '';
        $req = new \UnionOpenGoodsBigfieldQueryRequest();
        $goodsReq = new GoodsReq();
        $goodsReq->setSkuIds($spu);
        $req->setGoodsReq($goodsReq);
        $req->setSkuIds($spu);
        $req->setVersion("1.0");
        $resp = $jdc->execute($req, $jdc->accessToken);
        halt($resp);
    }

    // 文档地址 https://github.com/yumufeng/jd-union-sdk
    protected function getJdDetail($spu)
    {
        $client = new JdFatory($this->config);
        return $client->good->bigFieldQuery($spu, '');
    }

    // 获取价格
    protected function getJdPrice($spu)
    {
        $client = new JdFatory($this->config);
        $result = $client->good->info($spu);
        halt($result);
    }

    public function baseCollect($spu)
    {
        set_time_limit(0);
        $ql = new QueryList ();
        $url_pc = 'https://item.jd.com/' . $spu . '.html';
        $goods_info = array();
        $goods_info ['goods_unit'] = '';
        $goods_info ['brand_name'] = '';
        $goods_info ['product_area'] = '';
        $goods_info ['goods_model'] = '';
        /*$url = 'https://item.m.jd.com/product/' . $spu . '.html';
        $base_html = $ql->get($url, '', [
            "headers" => [
                "User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0"
            ]
        ]);
        $goods_pics = $base_html->find('script')->texts();

        if (!isset ($goods_pics [7])) {
            halt('未采集型号等信息');
        } else {
            //$result = array();
            $temp = explode('({', $goods_pics [7]);
            $temp = explode('})', $temp [1]);
            $t = json_decode(str_replace('"item": ', '', $temp [0]), true);
            $goods_info ['goods_unit'] = $t ['saleUnit'] ?? '';
            $goods_info ['brand_name'] = $t ['brandName'] ?? '';
            $goods_info ['product_area'] = $t ['productArea'] ?? '';
            $goods_info ['goods_model'] = $t ['model'] ?? $t['ColorSize'][0]['Size'] ?: $t['ColorSize'][0]['Color'];
        }*/
        //$description = $t ['description'];
        $get_content = $this->getJdDetail($spu);
        $t ['image'] = $get_content['imageInfo'];
        $jdc = new \JdClient();
        $jdc->appKey = '8a13ee6e602e39355ca3ac4ee05e24ac';
        $jdc->appSecret = 'ee3b7e41ac494be4b1aaf74b26a5fe2e';
        $jdc->accessToken = "";
        $req = new \UnionOpenGoodsBigfieldQueryRequest();
        $skuarr = [];
        $skuarr['skuIds'] = [];
        array_push($skuarr['skuIds'],$spu);
        $req->setGoodsReq($skuarr);
        $resp = $jdc->execute($req, $jdc->accessToken);
        $goods_attr = [];
        if (isset($resp->jd_union_open_goods_bigfield_query_responce->queryResult)) {
            $jd_json = $resp->jd_union_open_goods_bigfield_query_responce->queryResult;
            $jd_data = json_decode($jd_json, true);
            if (isset($jd_data['data'][0])) {
                $attr_arr = [];
                if(isset($jd_data['data'][0]['baseBigFieldInfo']['propGroups'])) {
                    $attr_arr = json_decode($jd_data['data'][0]['baseBigFieldInfo']['propGroups'], true);
                }

                foreach ($attr_arr as $key=>$val){
                    $ts1['groupName'] = $val['groupName'];
                    $ts1['atts'] = array();
                    foreach ($val['atts'] as $k=>$v){
                        $ts2['attName'] = $v['attName'];
                        $ts2['vals'] = $v['vals'];
                        $ts2['sort'] = $v['sort'];
                        array_push($ts1['atts'],$ts2);
                    }
                    array_push($goods_attr,$ts1);
                }
            }
        }

        $req1 = new \UnionOpenGoodsPromotiongoodsinfoQueryRequest();
        $req1->setSkuIds($spu);
        $resp = $jdc->execute($req1, $jdc->accessToken);
        if (isset($resp->jd_union_open_goods_promotiongoodsinfo_query_responce->queryResult)) {
            $jd_json = $resp->jd_union_open_goods_promotiongoodsinfo_query_responce->queryResult;
            $jd_data = json_decode($jd_json, true);
            if (!isset($jd_data['data'][0])) {
                //$this->layuiReturn('商品下架或非推广商品');
                $goods_info ['price'] = 0;
            } else {
                //$goods_info ['goods_name'] = $jd_data['data'][0]['goodsName'];
                $goods_info ['price'] = $jd_data['data'][0]['unitPrice'];
            }
        }
        $goods_info ['goods_name'] = $get_content['sku_name'];
        // 处理图片
        $goods_info ['goods_pictures'] = [];

        if (isset ($t ['image'])) {
            $uploaddb = new Uploaddb ();
            foreach ($t ['image'] as $key => $val) {
                //$val = 'https://m.360buyimg.com/mobilecms/s843x843_' . $val;
                array_push($goods_info ['goods_pictures'], $val['url']);

            }
            if (isset($this->post['set_location']) && $this->post['set_location'] == 'yes') {
                $mulu = date('Ymd') . '/';
                $dir = './uploads/' . $mulu;
                if (!is_dir($dir)) @mkdir($dir, 0777);
                $upload_save = [];
                foreach ($goods_info ['goods_pictures'] as $key => $val) {
                    $get_file = file_get_contents($val);
                    $file_name = time() . rand(1000, 9999) . '.' . substr($val, -3, 3);
                    if ($get_file) {
                        $fp = @fopen($dir . $file_name, "w");
                        @fwrite($fp, $get_file);
                        @fclose($fp);
                    }
                    $temp = [];
                    $temp['file_name'] = $file_name;
                    $temp['save_path'] = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/' . $mulu . $file_name;
                    $temp['type'] = 'image/jpeg';
                    $temp['size'] = 1000;
                    array_push($upload_save, $temp);
                }
                $get_upload_data = $uploaddb->saveAll($upload_save);
                $goods_info['upload_info'] = [];
                foreach ($get_upload_data as $key => $val) {
                    //$val['save_path'] = $val['save_path'];
                    array_push($goods_info['upload_info'], $val);
                }
            }
        }
        $goods_info['content'] = $get_content['content'];
        // 属性
        /*$attr_url = 'https://wq.jd.com/commodity/itembranch/getspecification?callback=commParamCallBackA&skuid=' . $spu;
        $goods_attr = $ql->get($attr_url)->getHtml();
        $attr = str_replace('commParamCallBackA(', '', $goods_attr);
        $attr = str_replace('})', '}', $attr);
        $attr = json_decode($attr, true);
        $goods_attr = $attr ['data'] ['propGroups']?:[];*/
        // 基础属性
        /*$agent = array(
            'User-Agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
            'User-Agent:Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
            'User-Agent:Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)',
            'User-Agent:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
            'User-Agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
            'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
            'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
            'User-Agent:Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
            'User-Agent:Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11',
            'User-Agent:Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
            'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
            'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)',
            'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)',
            'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
            'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)',
            'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)',
            'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)',
            'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)',
            'User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
        );*/
        $pc_html = $ql->get($url_pc, [], [
            "headers" => [
                "User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0",
                "Cookie" => "7v9kujmgv8uqouoz9rnkfbox8afxfp3m",
                "Accept-Encoding" => "gzip, deflate, br",
                "origin" => "https://item.jd.com",
                "accept" => "*/*"
            ]
        ]);
        $get_base_attr = $pc_html->find('.parameter2 li')->htmls();
        $base_attr_arr = array();
        $base_attr_arr ['groupName'] = '基础属性';
        $base_attr_arr ['atts'] = array();
        for ($i = 0; $i < count($get_base_attr); $i++) {
            $temp1 = explode('：', $get_base_attr [$i]);
            if ($temp1 [1]) {
                $t1 = array();
                $t1 ['attName'] = $temp1 [0];
                $str = htmlspecialchars_decode($temp1 [1]);
                $str = preg_replace("/<a[^>]*>(.*?)<\/a>/is", "$1", $str);
                $t1 ['vals'] = array(
                    $str
                );
                $t1['sort'] = ($i + 1);
                array_push($base_attr_arr ['atts'], $t1);
            }
        }
        array_push($goods_attr, $base_attr_arr);
        // 基础属性结束
        $goods_info ['goods_attr'] = $goods_attr;
        $attr_html = '<div style="display:flex;flex-wrap:wrap;">';
        foreach ($goods_attr as $key => $val) {
            $attr_html .= '<div style="width:220px"><div style="padding-left:10px;font-size:16px;font-weight:600">' . $val ['groupName'] . '</div><div style="padding-left:20px">';
            foreach ($val ['atts'] as $k => $v) {
                $attr_html .= '<div>' . $v ['attName'] . '：' . $v ['vals'] [0] . '</div>';
            }
            $attr_html .= '</div></div>';
        }
        $attr_html .= '</div>';
        $rh = '<div>商品名称：' . $goods_info ['goods_name'] . '</div>';
        $rh .= '<div>商品型号：' . $goods_info ['goods_model'] . '</div>';
        $rh .= '<div>商品品牌：' . $goods_info ['brand_name'] . '</div>';
        $rh .= '<div>商品产地：' . $goods_info ['product_area'] . '</div>';
        $rh .= '<div>商品单位：' . $goods_info ['goods_unit'] . '</div>';
        $rh .= '<div>商品价格：' . $goods_info ['price'] . '</div>';
        $rh .= '<div>图片地址：' . implode('<br />', $goods_info ['goods_pictures']) . '</div>';

        $rh .= '<div>商品属性：</div>';
        $rh .= $attr_html;

        $this->layuiReturn($goods_info, $rh, 'success', 1);
    }

    public function baseCollectWap($spu)
    {
        set_time_limit(0);
        $url = 'https://item.m.jd.com/product/' . $spu . '.html';
        // $url = 'https://item.jd.com/' . $spu . '.html';
        $ql = new QueryList ();
        $base_html = $ql->get($url);
        $goods_pics = $base_html->find('script')->texts();
        if (!isset ($goods_pics [7])) {
            $this->layuiReturn('商品编号错误', 1, 'error', 0);
        }
        $result = array();
        $temp = explode('({', $goods_pics [7]);
        $temp = explode('})', $temp [1]);
        $t = json_decode(str_replace('"item": ', '', $temp [0]), true);
        $goods_info = array();
        $goods_info ['goods_name'] = $t ['skuName'];
        $goods_info ['goods_unit'] = $t ['saleUnit'];
        $goods_info ['brand_name'] = $t ['brandName'];
        $goods_info ['product_area'] = $t ['productArea'];
        $goods_info ['goods_model'] = $t ['model'];
        $description = $t ['description'];
        // 价格
        $price_url = 'https://pe.3.cn/prices/mgets?skuids=' . $spu;
        $goods_price = $ql->get($price_url)->getHtml();
        $price = json_decode($goods_price, true);
        $goods_info ['price'] = $price [0] ['p'];
        // 处理图片
        $goods_info ['goods_pictures'] = [];
        if (isset ($t ['image'])) {
            $uploaddb = new Uploaddb ();
            foreach ($t ['image'] as $key => $val) {
                $val = 'https://m.360buyimg.com/mobilecms/s843x843_' . $val;
                array_push($goods_info ['goods_pictures'], $val);
            }
        }
        // 详情
        $content_url = 'https://cd.jd.com/description/channel?skuId=' . $spu . '&mainSkuId=' . str_replace('d', '', $description) . '&charset=utf-8&cdn=2&callback=showdesc';
        // $content_url = 'https://wqsitem.jd.com/detail/' . $spu . '_' . $description . '_normal.html';
        $goods_content = $ql->get($content_url)->getHtml();
        // 正则验证内容图片属于背景图
        $preg_title = "|url\((.*)\);|U";
        preg_match_all($preg_title, $goods_content, $bg_img);
        $content = '';
        foreach ($bg_img [1] as $key => $val) {
            $content .= '<div><img src="' . $val . '" /></div>';
        }
        $goods_info ['content'] = $content;
        // 属性
        $attr_url = 'https://wq.jd.com/commodity/itembranch/getspecification?callback=commParamCallBackA&skuid=' . $spu;
        $goods_attr = $ql->get($attr_url)->getHtml();
        $attr = str_replace('commParamCallBackA(', '', $goods_attr);
        $attr = str_replace('})', '}', $attr);
        $attr = json_decode($attr, true);
        $goods_attr = $attr ['data'] ['propGroups'];
        $goods_info ['goods_attr'] = $goods_attr;
        $attr_html = '<div style="display:flex;flex-wrap:wrap;">';
        foreach ($goods_attr as $key => $val) {
            $attr_html .= '<div style="width:220px"><div style="padding-left:10px;font-size:16px;font-weight:600">' . $val ['groupName'] . '</div><div style="padding-left:20px">';
            foreach ($val ['atts'] as $k => $v) {
                $attr_html .= '<div>' . $v ['attName'] . '：' . $v ['vals'] [0] . '</div>';
            }
            $attr_html .= '</div></div>';
        }
        $attr_html .= '</div>';
        $rh = '<div>商品名称：' . $goods_info ['goods_name'] . '</div>';
        $rh .= '<div>商品型号：' . $goods_info ['goods_model'] . '</div>';
        $rh .= '<div>商品品牌：' . $goods_info ['brand_name'] . '</div>';
        $rh .= '<div>商品产地：' . $goods_info ['product_area'] . '</div>';
        $rh .= '<div>商品单位：' . $goods_info ['goods_unit'] . '</div>';
        $rh .= '<div>商品价格：' . $goods_info ['price'] . '</div>';
        $rh .= '<div>图片地址：' . implode('<br />', $goods_info ['goods_pictures']) . '</div>';

        $rh .= '<div>商品属性：</div>';
        $rh .= $attr_html;
        $this->layuiReturn($goods_info, $rh, 'success', 1);
    }

    public function saveCollect()
    {
        $goods_sku = 'SKU' . base_convert(uniqid(), 16, 10);
        $category_sign = $this->post ['category_sign3'];
        $spu = $this->post ['spu'];
        if ($category_sign == '') {
            $this->layuiReturn('没有三级目录', 0, 'error', 0);
        }
        set_time_limit(0);
        $goods_info ['goods_name'] = $this->post ['goods_name'];
        $goods_info ['goods_unit'] = $this->post ['goods_unit'];
        $goods_info ['brand_name'] = $this->post ['brand_name'];
        $goods_info ['product_area'] = $this->post ['product_area'];
        $goods_info ['goods_model'] = $this->post ['goods_model'];
        // 价格
        $goods_info ['price'] = $this->post ['price'];
        $jddb = new Jddb ();
        $jddb->param ['goods_name'] = $goods_info ['goods_name'];
        $jddb->param ['goods_model'] = $goods_info ['goods_model'];
        $jddb->param ['goods_unit'] = $goods_info ['goods_unit'];
        $jddb->param ['product_area'] = $goods_info ['product_area'];
        $jddb->param ['brand_name'] = $goods_info ['brand_name'];
        $jddb->param ['goods_sku'] = $goods_sku;
        $jddb->param ['new_price'] = $goods_info ['price'];
        $jddb->param ['price'] = $goods_info ['price'];
        $jddb->param ['spu'] = $spu;
        $chk_jd = $jddb->ajaxSave();
        if ($chk_jd == 'success') {
            // 处理品牌
            $branddb = new Branddb ();
            $chk_brand = $branddb->chkFind($goods_info ['brand_name']);
            if (isset ($chk_brand ['brand_sign'])) {
                // 已存在品牌
                $brand_sign = $chk_brand ['brand_sign'];
            } else {
                // 不存在品牌
                $branddb->param ['brand_name'] = $goods_info ['brand_name'];
                $branddb->param ['api_option'] = '';
                $branddb->ajaxSave();
                $brand_sign = $branddb->last_brand_sign;
            }
            // 验证品牌是否存在于分类下
            $categoryBranddb = new CategoryBranddb ();
            $categoryBranddb->param ['category_sign'] = $category_sign;
            $categoryBranddb->param ['brand_sign'] = $brand_sign;
            $chk_cb = $categoryBranddb->ajaxFind();
            if (!isset ($chk_cb ['category_brand_id'])) {
                // 分类下没有品牌 录入数据
                $categoryBranddb->ajaxSave();
            }
            // 品牌处理完成
            // 处理图片
            $goods_info ['goods_pictures'] = [];
            $uploaddb = new Uploaddb ();
            foreach ($this->post ['goods_pictures'] as $key => $val) {
                $uploaddb = new Uploaddb ();
                $uploaddb->param ['save_path'] = $val;
                $uploaddb->param ['file_name'] = time() . 'png';
                $uploaddb->param ['is_outlink'] = 2;
                $uploaddb->param ['type'] = 'image/jpeg';
                $uploaddb->param ['size'] = 100;
                $get_upload = $uploaddb->ajaxAddOne();
                array_push($goods_info ['goods_pictures'], $get_upload);
            }
            $goods_info ['goods_picture'] = $goods_info ['goods_pictures'] [0];
            // 图片处理结束
            // 正则验证内容图片属于懒加载
            $goods_info ['goods_content'] = $this->post ['content'];
            $goods_info ['goods_sku'] = $goods_sku;
            $goods_info ['category_sign1'] = $this->post ['category_sign1'];
            $goods_info ['category_sign2'] = $this->post ['category_sign2'];
            $goods_info ['category_sign3'] = $this->post ['category_sign3'];
            $goods_info ['category_sign'] = $category_sign;
            $goods_info ['brand_sign'] = $brand_sign;
            $goodsdb = new Goodsdb ();
            $goodsdb->save($goods_info);
            // 开始处理商品属性

            $value_data = array();
            $attrValuedb = new AttrValuedb ();

            $k = 0;
            $goods_attr = $this->post ['goods_attr'];
            for ($i = 0; $i < count($goods_attr); $i++) {
                $group_name = $goods_attr [$i] ['groupName'];
                if (isset($goods_attr [$i] ['atts'])) {
                    foreach ($goods_attr [$i] ['atts'] as $k => $v) {
                        // 获取属性编号
                        $attrdb = new Attrdb ();
                        $attrdb->param ['category_sign'] = $category_sign;
                        $attrdb->param ['jd_name'] = $v ['attName'];
                        $attrdb->param['group_name'] = $group_name;
                        $chk_attr = $attrdb->ajaxChkFind();
                        if (isset ($chk_attr ['attr_sign'])) {
                            $attr_sign = $chk_attr ['attr_sign'];
                            if ($chk_attr['value_type'] == 3) {
                                // 如果有属性 验证属性值是否存在
                                // $attrdb->param ['value_item'] = implode ( ',', $v ['vals'] );
                                $chk_attr_item = explode(',', $chk_attr ['value_item']);
                                for ($i1 = 0; $i1 < count($v ['vals']); $i1++) {
                                    $chk_flag = 1;
                                    for ($j1 = 0; $j1 < count($chk_attr_item); $j1++) {
                                        if ($v ['vals'][$i1] == $chk_attr_item [$j1]) {
                                            $chk_flag = 2;
                                        }
                                    }
                                    if ($chk_flag == 1) {
                                        array_push($chk_attr_item, $v ['vals'] [$i1]);
                                    }
                                }
                                $attrdb->where('attr_id', $chk_attr ['attr_id'])->update([
                                    'value_item' => implode(',', $chk_attr_item)
                                ]);
                            }
                        } else {
                            $attrdb = new Attrdb ();
                            $attrdb->param ['value_item'] = implode(',', $v ['vals']);
                            $attrdb->param ['value_type'] = 3;
                            $attrdb->param ['select_type'] = 2;
                            $attrdb->param ['attr_sign'] = md5(time() . round(1000, 9999) . uniqid());
                            $attrdb->param ['category_sign'] = $category_sign;
                            $attrdb->param ['group_name'] = $group_name;
                            $attrdb->param ['attr_name'] = $v ['attName'];
                            $attrdb->param ['jd_name'] = $v ['attName'];
                            $attrdb->param ['sort'] = $v ['sort'];
                            $attrdb->param ['is_must'] = 2;
                            if ($group_name == '基础属性') {
                                $attrdb->param ['value_type'] = 1;
                                $attrdb->param ['value_item'] = '';
                            }
                            $attrdb->param ['unit'] = '';

                            $attrdb->ajaxSave();
                            $attr_sign = $attrdb->lastInsSign;
                        }
                        // 下面处理属性值
                        $temp ['goods_sku'] = $goods_info ['goods_sku'];
                        $temp ['attr_sign'] = $attr_sign;
                        $temp ['attr_value'] = implode(',', $v ['vals']);
                        $temp ['partner_id'] = PARTNER_ID;
                        $temp ['site_id'] = SITE_ID;
                        array_push($value_data, $temp);
                    }
                }
            }
            $attrValuedb->saveAll($value_data);
            // 属性处理完成 处理价格
            $salePricedb = new SalePricedb ();
            $data_price ['partner_id'] = PARTNER_ID;
            $data_price ['site_id'] = SITE_ID;
            $data_price ['goods_sku'] = $goods_info ['goods_sku'];
            $data_price ['market_price'] = $goods_info ['price'];
            $data_price ['sale_price'] = $goods_info ['price'];
            $data_price ['api_price'] = $goods_info ['price'];
            $data_price ['give_score'] = 0;
            $data_price ['view_stock'] = 9999;
            $data_price ['sale_attr_price_name'] = '商品价格';
            $data_price ['sale_price_sign'] = md5(time() . uniqid());
            $salePricedb->allowField(true)->save($data_price);
            Cache::clear();
            $this->layuiReturn('录入成功', 1, 'success', 1);
        } else {
            $this->layuiReturn('错误', 0, 'error', 0);
        }
    }
}